package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.util.Metrics;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        // 1. 缓存穿透
        Shop shop = queryWithPassThrough(id);

        // 2. 互斥锁解决缓存击穿
        // Shop shop = queryWithMutex(id);

        // 3. 逻辑过期解决缓存击穿
        // Shop shop = queryWithLogicalExpireTime(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }

        // 7. 存在，返回
        return Result.ok(shop);
    }

    private Shop queryWithMutex(Long id) {
        // 1. 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopMsg = stringRedisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopMsg)) {
            // 3. 存在，返回
            Shop shop = JSONUtil.toBean(shopMsg, Shop.class);
            return shop;
        }

        //  如果缓存命中空值，但不是null（即查到的是空字符串""），说明之前缓存过空值，
        if (shopMsg != null) {
            return null;
        }

        // 4. 实现缓存重建
        // 4.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        boolean isLock = false;
        try {

            // 4.2 判断锁是否获取成功
            while (true) {
                isLock = tryLock(lockKey);
                if (isLock) {
                    break;
                }
                // 4.3 获取锁失败，休眠重试
                Thread.sleep(50);
            }

            // 4.4 二次检查，获取锁成功后判断缓存是否重建完成（可能别的线程提前获取互斥锁，在释放锁之前已经完成缓存重建）
            String shopMsg1 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopMsg1)) {
                shop = JSONUtil.toBean(shopMsg1, Shop.class);
                return shop;
            }
            // 4.5 若缓存还未重建，缓存重建
            shop = getById(id);
            // 模拟重建的延时
            Thread.sleep(100);

            // 5. 判断店铺是否存在
            if (shop == null) {
                // 数据库不存在，缓存空值
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            // 6. 存在，写入缓存并设置30分钟有效期
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7. 释放互斥锁、
            if (isLock) {
                unLock(lockKey);
            }
        }

        // 8. 返回
        return shop;
    }

    private Shop queryWithPassThrough(Long id) {
        // 1. 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopMsg = stringRedisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopMsg)) {
            // 3. 存在，返回
            Shop shop = JSONUtil.toBean(shopMsg, Shop.class);
            return shop;
        }

        //  如果缓存命中空值，但不是null（即查到的是空字符串""），说明之前缓存过空值，
        if (shopMsg != null) {
            return null;
        }

        // 4. 缓存未命中，查询数据库
        Shop shop = getById(id);

        // 5. 判断店铺是否存在
        if (shop == null) {
            // 数据库不存在，缓存空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        // 6. 存在，写入缓存并设置30分钟有效期
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7. 存在，返回
        return shop;
    }

    // 线程池
    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Shop queryWithLogicalExpireTime(Long id) {
        // 1. 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopMsg = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (StrUtil.isBlank(shopMsg)) {
            // 3. 不存在，返回null
            return null;
        }

        // 4. 命中，需要把数据从json转为对象
        RedisData redisData = JSONUtil.toBean(shopMsg, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        // 5. 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，返回数据
            return shop;
        }

        // 6 已过期，缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        // 6.1 获取互斥锁
        boolean isLock = tryLock(lockKey);

        // 6.2 判断锁是否获取成功
        if (isLock) {
            // 6.3 二次检查，获取锁成功后判断缓存是否重建完成
            String shopMsg1 = stringRedisTemplate.opsForValue().get(key);
            RedisData redisData1 = JSONUtil.toBean(shopMsg1, RedisData.class);
            LocalDateTime expireTime1 = redisData1.getExpireTime();
            JSONObject data1 = (JSONObject) redisData1.getData();
            if (expireTime1.isAfter(LocalDateTime.now())) {
                // 缓存已重建，返回数据
                return JSONUtil.toBean(data1, Shop.class);
            }
            // 6.4 缓存未重建，开启一个独立线程执行重建过程
            CACHE_REBUILD_EXECUTOR.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 重建缓存
                        saveShop2Redis(id, 30L);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        unLock(lockKey);
                    }
                }
            });
        }
        // 7. 返回旧数据，兜底
        return shop;
    }

    // 自定义获取锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 30L, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    // 释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    // 缓存预热
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        // 1. 查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);
        // 2. 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        // 在当前时间加上指定时间
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3. 写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 1. 更新数据库
        updateById(shop);

        // 2. 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }


    @Resource
    private IShopService shopService;

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1. 判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按照数据库查询
            Page<Shop> page = shopService.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 2. 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 3. 查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        // 4. 查询1500km范围内的店铺的id
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok();
        }
        // 5. 截取from~end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> map = new HashMap<>(list.size());
        list.stream().skip(from).forEach(item -> {
            // 获取店铺id
            String shopIdStr = item.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = item.getDistance();
            map.put(shopIdStr, distance);
        });

        String idStr = StrUtil.join(",", ids);

        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        for (Shop shop : shops) {
            Distance distance = map.get(shop.getId().toString());
            shop.setDistance(distance.getValue());
        }

        // 6. 返回
        return Result.ok(shops);
    }
}
